﻿//Copyright (C) <2013>  <jonathan cleeve norton> All Rights Reserved 
//Contact jon.norton@fin-plus.co.uk website <http://www.fin-plus.co.uk/>
using System;
using System.Linq;
using System.ComponentModel;
using FinPlusCommon;
using log = Logger.Logger;

namespace FinPlusComponents
{
    public class FinPlusTradeRegister : FinPlusComponent
    {
        private enum Params { ReceiveQuoteAction, ParseTradeAction, InstrumentType }
        private IFinPlusComp _tradeAdaptorConn;
        private IFunctions _tradeAdaptors;

        //construct
        public FinPlusTradeRegister(IFinPlusComp tradeAdaptors)
        {
            _tradeAdaptorConn = tradeAdaptors;
            _tradeAdaptors = _tradeAdaptorConn.Adaptor;
            foreach (var tradeAdaptor in _tradeAdaptors.Values)
                tradeAdaptor.Get(Params.ReceiveQuoteAction.ToString(), Quote_Accepted);
            IsValid = true;
        }

        //common control interface
        public override void CmdExecute(IFunction command)
        {
            try
            {
                CmdCapture(command);

                switch ((Cmds)Enum.Parse(typeof(Cmds), command.Name, true))
                {
                    case Cmds.QuoteAccept: QuoteParse(command); break;
                    case Cmds.QuoteAcceptPublish: QuoteParse(command); break;
                    default: throw new FormatException(string.Format("event not recognised {0}", command.Name));
                }
            }
            catch (CmdExecuteException e)
            {
               IsValid = log.Log(Logger.Level.Error, Id, Config, e.Message, e);
            }
        }

        //private
        private bool QuoteParse(IFunction func)
        {
            try
            {
                //TODO save execution for audit and check
                //Save exection for reconcile to parse trades and audit

                //send back to adaptor for Trade parser
                foreach (var tradeAdaptor in _tradeAdaptors.Values.Where(f => f[Params.InstrumentType.ToString()].Equals(func[Params.InstrumentType.ToString()])))
                    tradeAdaptor.Get(Params.ParseTradeAction.ToString()).Set(func); //to trade engine

            }
            catch (Exception e)
            {
                log.Log(Logger.Level.Error, Id, Config, e.Message, e);
            }

            return true;
        }

        //cmds
        private enum Cmds { QuoteAccept, QuoteAcceptPublish };

        //events
        private void Quote_Accepted(object s, PropertyChangedEventArgs a) { CmdRouter(s); }//QuoteAccept && QuotePublishAccept
    }
}
